var appConfig, myMap, view_3D, view_2D, view_2D_second, Map_Layers, MapExtent_t;
var Popup_Buttons;
var map_draw_type = 0, map_draw_geometry = "";
var point_click, selectedFeature, searchFeature;
var Draw_Graphic_Mouse_Click, Draw_Graphic, Point_Map_Click = [];
var MarkerSymbol, PolygonSymbol, LineSymbol;
var graphicsLayer_buffer, graphicsLayer_search;
var Kriging_GP, Kriging_GP_z_field;
var spatialReference_ID;

require(["esri/config", "esri/Map", "esri/geometry/geometryEngine",
    "esri/widgets/Print",
    "esri/layers/ElevationLayer", "esri/layers/MapImageLayer", "esri/views/MapView", "esri/views/SceneView", "esri/renderers/SimpleRenderer",
    "esri/layers/TileLayer",
    "esri/symbols/TextSymbol", "esri/symbols/SimpleFillSymbol", "esri/symbols/SimpleLineSymbol", "esri/symbols/SimpleMarkerSymbol",
    "esri/geometry/Point", "esri/geometry/Multipoint", "esri/geometry/Polyline", "esri/geometry/Polygon",
    "esri/layers/FeatureLayer",
    "esri/layers/GraphicsLayer", "esri/Graphic", "esri/widgets/Search",
    "esri/tasks/QueryTask", "esri/tasks/support/Query", "esri/tasks/Geoprocessor","esri/tasks/support/FeatureSet",
    "esri/layers/support/ImageParameters",
    "esri/widgets/Home", "esri/widgets/Compass",
    "dojo/on", "dojo/dom", "dojo/domReady!"],
    function (esriConfig, Map, geometryEngine,
        Print,
        ElevationLayer, MapImageLayer, MapView, SceneView, SimpleRenderer,
        TileLayer,
        TextSymbol, SimpleFillSymbol, SimpleLineSymbol, SimpleMarkerSymbol,
        Point, Multipoint, Polyline, Polygon,
        FeatureLayer,
        GraphicsLayer, Graphic, Search,
        QueryTask, Query, Geoprocessor,FeatureSet,
        ImageParameters,
        Home, Compass,
        on, dom) {
        appConfig = { mapView: null, sceneView: null, activeView: null, container: "mapDiv" };
        //画图样式symbol
        PolygonSymbol = new SimpleFillSymbol({ outline: { color: [255, 0, 0], width: 2 } });
        LineSymbol = new SimpleLineSymbol({ color: [255, 0, 0], width: 2 });
        MarkerSymbol = new SimpleMarkerSymbol({ color: [255, 0, 0], size: 8, outline: { color: [255, 255, 255], width: 1 } });
        var MarkerSymbol_Mouse = new SimpleMarkerSymbol({ style: "cross", color: [255, 0, 0], size: 10, outline: { color: [255, 0, 0], width: 1 } });
        var swapButton = document.getElementById("swap-btn");
        var PrintService_URL;
        var json_file_name = "js/map_set.json";
        $.getJSON(json_file_name, function (data) {
            if (data.Server_Port != null && data.Server_Port.length > 0) {
                for (var i = 0; i < data.Server_Port.length; i++) {
                    //把服务托管，解决跨域问题
                    esriConfig.request.corsEnabledServers.push(data.Server_Port[i]);
                }
            }
            spatialReference_ID = data.spatialReference;
            MapExtent_t = data.MapExtent;   //地图初始化范围
            Map_Layers = data.Map_Layers;   //Array[13] 13个图层组成数组
            Popup_Buttons = data.Popup_Buttons; //Array[11] 11个弹出button组成数组
            // 加载地图服务-----------------------------------------------------------------------------
            var Services = data.Services;
            if (Services != null && Services.length > 0) {
                for (var i = 0; i < Services.length; i++) {
                    var Map_Service = Services[i];
                    var name = Map_Service.Name;
                    var url = Map_Service.URL;
                    if (name == "PrintService") {
                        PrintService_URL = url;
                    } else if (name == "KrigingService") {
                        Kriging_GP = new Geoprocessor(url);
                        Kriging_GP.outSpatialReference = { // autocasts as new SpatialReference()
                            wkid: spatialReference_ID
                        };
                        Kriging_GP_z_field = Map_Service.z_field;
                    }
                }
            }

            myMap = new Map();
            if (data.Basemap != null) { myMap.basemap = data.Basemap; }
            if (data.Ground != null) { myMap.ground = data.Ground; }
            // 加载地图图层-----------------------------------------------------------------------------
            var Map_Layer_POI;
            for (var i = 0; i < Map_Layers.length; i++) {
                var Map_Layer = Map_Layers[i];
                var name = Map_Layer.Name;
                if (name == "POI") {
                    Map_Layer_POI = Map_Layer;
                }
                if (Map_Layer.Add_Layer) {
                    var layer = may_layer_start(Map_Layer);
                    myMap.layers.add(layer);
                }
            }
            graphicsLayer_buffer = new GraphicsLayer();
            graphicsLayer_buffer.on('click', function (ex) {
                alert(11111)
            })
            myMap.layers.add(graphicsLayer_buffer);

            graphicsLayer_search = new GraphicsLayer();
            myMap.layers.add(graphicsLayer_search);

            //高程
            if (data.Elevation_Layers != null) {
                var Elevation_Layers = data.Elevation_Layers;
                for (var i = 0; i < Elevation_Layers.length; i++) {
                    var elevationLayer = new ElevationLayer({ url: Elevation_Layers[i].URL });
                    myMap.ground.layers.add(elevationLayer);
                }
            }
            var Center_Point = new Point({ x: MapExtent_t.Center_Point.x, y: MapExtent_t.Center_Point.y, spatialReference: spatialReference_ID });
            var initialViewParams = {
                container: appConfig.container,     // Reference to the scene div created in step 5
                map: myMap,                 // Reference to the map object created before the scene
                center: Center_Point,  // Sets the center point of view with lon/lat
                zoom: MapExtent_t.Zoom
            };

            //图层设置
            function may_layer_start(Map_Layer) {
                var name = Map_Layer.Name;
                var Layer_Type = Map_Layer.Layer_Type;
                var url = Map_Layer.URL;

                var layer;
                if (Layer_Type == "TileLayer" | "ArcGISLocalTiledLayer" | Layer_Type == "ArcGISTiledMapServiceLayer") {
                    layer = new TileLayer({ url: url, id: name });
                } else if (Layer_Type == "MapImageLayer" | "ArcGISDynamicMapServiceLayer") {
                    layer = new MapImageLayer({ url: url, id: name });
                } else if (Layer_Type == "FeatureLayer" || Layer_Type == "GeoJson") {
                    if (Layer_Type == "GeoJson") {
                        layer = get_GeoJson_layer(Map_Layer);
                    } else {
                        layer = new FeatureLayer({ url: url, outFields: ["*"], opacity: Map_Layer.opacity, returnZ: true, id: name });
                    }
                    if (Map_Layer.definitionExpression != null) {
                        layer.definitionExpression = Map_Layer.definitionExpression;
                    }
                    if (Map_Layer.UniqueValueRenderer != null) {
                        var Renderer = new UniqueValueRenderer({ field: Map_Layer.UniqueValueRenderer });
                        var Symbols = Map_Layer.Symbols;
                        for (var ii = 0; ii < Symbols.length; ii++) {
                            var Symbol_i = Symbols[ii];
                            var symbol = Symbol_i;
                            Renderer.addUniqueValueInfo(Symbol_i.Data, symbol);
                        }
                        layer.renderer = Renderer;
                    } else {
                        if (Map_Layer.Symbols != null) {
                            var symbol = Map_Layer.Symbols;
                            layer.renderer = new SimpleRenderer({ symbol: symbol });
                        }
                    }
                    if (Map_Layer.Popup != null) {
                        layer.popupTemplate = Popup_template_set(Map_Layer.Popup);
                    }
                    if (Map_Layer.elevationInfo != null) {
                        layer.elevationInfo = { mode: Map_Layer.elevationInfo };
                        if (Map_Layer.offset != null) {
                            layer.elevationInfo.offset = Map_Layer.offset;
                        }
                    }
                    if (Map_Layer.definitionExpression != null) {
                        layer.definitionExpression = Map_Layer.definitionExpression;
                    }
                    if (Map_Layer.screenSizePerspectiveEnabled != null) {
                        layer.screenSizePerspectiveEnabled = Map_Layer.screenSizePerspectiveEnabled;
                    }
                }

                if (Map_Layer.maxScale != null) {
                    layer.maxScale = Map_Layer.maxScale;
                }
                if (Map_Layer.minScale != null) {
                    layer.minScale = Map_Layer.minScale;
                }
                if (Map_Layer.Visible != null) {
                    layer.visible = Map_Layer.Visible;
                }
                if (Map_Layer.opacity != null) {
                    layer.opacity = Map_Layer.opacity;
                }
                return layer;
            }

            if (data.MapView_Change) {
                swapButton.style.visibility = "visible";
            }

            if (data.MapView == "3D") {
                createView(initialViewParams, "3d");
                appConfig.sceneView = view_3D;
                appConfig.activeView = appConfig.sceneView;
                initialViewParams.container = null;
                createView(initialViewParams, "2d");
                appConfig.mapView = view_2D;
                swapButton.value = "3D";
            } else {
                createView(initialViewParams, "2d");
                appConfig.mapView = view_2D;
                appConfig.activeView = appConfig.mapView;
                initialViewParams.container = null;
                createView(initialViewParams, "3d");
                appConfig.sceneView = view_3D;
                swapButton.value = "2D";
            }

            // 创建二维或者三维场景
            function createView(params, type) {
                var is2D = type === "2d";
                if (is2D) {
                    view_2D = new MapView(params);
                    var compass = new Compass({ view: view_2D });
                    view_2D.ui.add(compass, "top-left");
                    var homeBtn = new Home({ view: view_2D });
                    view_2D.ui.add(homeBtn, "top-left");
                } else {
                    view_3D = new SceneView(params);
                    var homeBtn = new Home({ view: view_3D });
                    view_3D.ui.add(homeBtn, "top-left");
                }
            }

            //如果有POI数据则加载搜索框
            if (Map_Layer_POI != null) {
                var popupTemplate = Popup_template_set(Map_Layer_POI.Popup);
                var FeatureLayer_POI = new FeatureLayer({
                    url: Map_Layer_POI.URL,
                    outFields: ["*"],
                    popupTemplate: popupTemplate
                });
                var searchWidget_3D = new Search({
                    view: view_3D,
                    allPlaceholder: "查找地名或地址",
                    sources: [{
                        featureLayer: FeatureLayer_POI,
                        searchFields: [Map_Layer_POI.SearchField],
                        displayField: Map_Layer_POI.SearchField,
                        exactMatch: false,
                        outFields: ["*"],
                        name: Map_Layer_POI.Name,
                        placeholder: "查找地名或地址"
                    }]
                });
                view_3D.ui.add(searchWidget_3D, { position: "top-right" });

                var searchWidget_2D = new Search({
                    view: view_2D,
                    allPlaceholder: "查找地名或地址",
                    sources: [{
                        featureLayer: FeatureLayer_POI,
                        searchFields: [Map_Layer_POI.SearchField],
                        displayField: Map_Layer_POI.SearchField,
                        exactMatch: false,
                        outFields: ["*"],
                        name: Map_Layer_POI.Name,
                        placeholder: "查找地名或地址"
                    }]
                });
                view_2D.ui.add(searchWidget_2D, { position: "top-right" });
            }

            var featureSet_map_click;
            // 注册地图单击事件-----------------------------------------------------------------------------
            view_3D.on("click", view_map_click);
            view_2D.on("click", view_map_click);
            function view_map_click(event) {
                point_click = new Point({ x: event.mapPoint.x, y: event.mapPoint.y, spatialReference: spatialReference_ID });
                if (map_draw_geometry != "") {
                    event.stopPropagation();
                    Draw_Map_Graphic();
                }
            }
            //画图工具字段的判定————画图界面、查询界面、统计界面、巡检界面、横断面分析界面区分
            function Draw_Map_Graphic() {
                if (map_draw_type == 0) {
                    Draw_Map_Graphic_sub(graphicsLayer_buffer, map_draw_geometry);
                }
                else if (map_draw_type == 1) {
                    Draw_Map_Graphic_sub(graphicsLayer_buffer, map_draw_geometry);
                }
                else if (map_draw_type == 2) {
                    Draw_Map_Graphic_sub(graphicsLayer_buffer, map_draw_geometry);
                }
                else if (map_draw_type == 3) {
                    Pane_visible('Pane_Baoxiu_Popup');
                    map_draw_end();
                    map_draw_type = 0;
                }
                else if (map_draw_type == 4) {
                    Draw_Map_Graphic_sub(graphicsLayer_xunjian, map_draw_geometry);
                }
                else if (map_draw_type == 8) {
                    Draw_Map_Graphic_sub(graphicsLayer_buffer, map_draw_geometry);//横断面分析界面
                }
                else if (map_draw_type == 11) {//巡检区域绘制                    
                    Draw_Map_Graphic_sub(graphicsLayer_buffer, map_draw_geometry);
                }
                else if (map_draw_type == 12 || map_draw_type == 13) {//巡检路线绘制                                      
                    Draw_Map_Graphic_sub(graphicsLayer_buffer, map_draw_geometry);
                }
            }
            //画图类型的选择————point,line,rectangle,polygon的区分
            function Draw_Map_Graphic_sub(graphicsLayer, type) {
                if (type == "point") {
                    add_Draw_Graphic(graphicsLayer, point_click, "point");
                } else {
                    if (Point_Map_Click.length == 0) {
                        Point_Map_Click.push([point_click.x, point_click.y]);
                        Draw_Graphic_Mouse_Click = new Graphic({ geometry: point_click, symbol: MarkerSymbol_Mouse });
                        graphicsLayer.add(Draw_Graphic_Mouse_Click);
                    } else {
                        if (Point_Map_Click.length > 1) {
                            graphicsLayer.remove(Draw_Graphic);
                        }
                        if (type == "line") {
                            Point_Map_Click.push([point_click.x, point_click.y]);
                            var polyline = new Polyline({ paths: Point_Map_Click, hasZ: false, spatialReference: spatialReference_ID });
                            add_Draw_Graphic(graphicsLayer, polyline, "line");
                        } else if (type == "rectangle") {
                            Point_Map_Click.push([Draw_Graphic_Mouse_Click.geometry.x, point_click.y]);
                            Point_Map_Click.push([point_click.x, point_click.y]);
                            Point_Map_Click.push([point_click.x, Draw_Graphic_Mouse_Click.geometry.y]);
                            var polygon = new Polygon({ rings: Point_Map_Click, hasZ: false, spatialReference: spatialReference_ID });
                            add_Draw_Graphic(graphicsLayer, polygon, "polygon");
                            graphicsLayer.remove(Draw_Graphic_Mouse_Click);
                            Point_Map_Click = [];
                        } else if (type == "polygon") {
                            Point_Map_Click.push([point_click.x, point_click.y]);
                            if (Point_Map_Click.length == 2) {
                                var polyline = new Polyline({ paths: Point_Map_Click, hasZ: false, spatialReference: spatialReference_ID });
                                add_Draw_Graphic(graphicsLayer, polyline, "line");
                            } else {
                                var polygon = new Polygon({ rings: Point_Map_Click, hasZ: false, spatialReference: spatialReference_ID });
                                add_Draw_Graphic(graphicsLayer, polygon, "polygon");
                            }
                        }
                        if (Point_Map_Click.length == 2) {
                            graphicsLayer.remove(Draw_Graphic_Mouse_Click);
                        }
                    }
                }
            }

            //菜单栏——图层checkbox-----------------------------------------------------------------------------
            var Div_layerList;
            Div_layerList = document.getElementById("Div_layerList");
            var _scroll_mh_div = document.createElement("div");
            _scroll_mh_div.className = '_panel-box';

            var _scroll_mh = document.createElement("div");
            _scroll_mh.className = '_scroll-mh je-pr all1-aa';
            _scroll_mh.appendChild(_scroll_mh_div);

            for (var i = Map_Layers.length - 1; i >= 0; i--) {
                var Map_Layer = Map_Layers[i];
                var name = Map_Layer.Name;
                var Add_Layer = Map_Layer.Add_Layer;
                if (Add_Layer) {
                    var BoxLay = document.createElement("div");
                    BoxLay.className = "boxlay";
                    BoxLay.style.textAlign = "left";

                    var layer_name = document.createElement("span");
                    layer_name.innerHTML = name;
                    BoxLay.appendChild(layer_name);

                    var BoxLay_label = document.createElement("label");
                    BoxLay_label.className = "boxlabel pr je-fr";

                    var layer_checkbox = document.createElement("input");
                    layer_checkbox.type = "checkbox";
                    layer_checkbox.className = 'boxinput pa';
                    layer_checkbox.value = i;
                    layer_checkbox.id = "checkbox_map_layer" + i;

                    layer_checkbox.onclick = function () { checkbox_LayerList(this); };
                    var littlepic = document.createElement("i");
                    if (Map_Layer.Visible != null) {
                        layer_checkbox.checked = Map_Layer.Visible;
                    } else {
                        layer_checkbox.checked = true;
                    }
                    if (layer_checkbox.checked == true) {
                        littlepic.innerHTML = '&#xe637;';
                        littlepic.className = 'icon boxlttle check cp active';
                    } else {
                        littlepic.className = 'icon boxlttle check cp';
                    }

                    BoxLay_label.appendChild(littlepic);
                    BoxLay_label.appendChild(layer_checkbox);
                    BoxLay.appendChild(BoxLay_label);
                    //图例
                    if (Map_Layer.Symbols != null) {
                        var Symbols_span;
                        if (Map_Layer.Symbols.length > 0) {
                            Symbols_span = Map_Layer.Symbols[0];
                        } else {
                            Symbols_span = Map_Layer.Symbols;
                        }
                        if (Symbols_span.type == "text") {
                            var span = document.createElement("span");
                            span.style.fontFamily = Symbols_span.font.family;
                            span.style.fontSize = "20px";
                            span.style.marginLeft = "5px";
                            span.style.color = Symbols_span.color;
                            span.innerHTML = Symbols_span.text;
                            BoxLay.appendChild(span);
                        }
                    }
                    _scroll_mh_div.appendChild(BoxLay);
                }
            }
            Div_layerList.appendChild(_scroll_mh);

            // 切换二三维地图
            swapButton.addEventListener("click", function () { swapView(); });
            function swapView() {
                appConfig.activeView.container = null;
                if (appConfig.activeView.type == "3d") {
                    appConfig.mapView.viewpoint = appConfig.activeView.viewpoint.clone();
                    appConfig.mapView.container = appConfig.container;
                    appConfig.activeView = appConfig.mapView;
                    swapButton.value = "2D";
                } else {
                    view_2D.ui.empty("bottom-left");
                    appConfig.sceneView.viewpoint = appConfig.activeView.viewpoint.clone();
                    if (appConfig.sceneView.viewpoint.scale < 4000) {
                        appConfig.sceneView.viewpoint.scale = 4513.988705;
                    }
                    appConfig.sceneView.container = appConfig.container;
                    appConfig.activeView = appConfig.sceneView;
                    swapButton.value = "3D";
                }
            }
            //注册地图trigger-action弹出框按钮单击事件
            view_3D.popup.on("trigger-action", popup_toolbar_click);
            view_2D.popup.on("trigger-action", popup_toolbar_click);
            function popup_toolbar_click(event) {
                if (event.action.id == "Popup_Buffer") {
                    if (appConfig.activeView.zoom > 9 || appConfig.activeView.zoom == -1) {
                        selectedFeature = appConfig.activeView.popup.viewModel.selectedFeature;
                        show_buffer();
                    } else {
                        alert('提示 请放大地图选择!');
                    }
                }
            }

            //缓冲区
            function show_buffer() {
                var buffer_distance = 3000;
                var geometry = selectedFeature.geometry;
                geometry.z = undefined;
                geometry.hasZ = false;
                if (geometry.rings != null) {
                    alert('缓冲区已经存在!');
                } else {
                    //利用geometryEngine的buffer在输入几何体周围的指定距离创建平面（或欧几里得）缓冲区多边形
                    var buffer_Geometry = geometryEngine.buffer(geometry, buffer_distance, "meters");
                    //把缓冲区集合对象添加到缓冲区图层中
                    add_Draw_Graphic(graphicsLayer_buffer, buffer_Geometry, "polygon");
                }
            };
            //缓冲区
            on(button_selectedFeature_buffer, "click", function () {
                var buffer_distance = Number(document.getElementById("Buffer_Text_distance").value);
                if (!isNaN(buffer_distance)) {
                    var geometry = selectedFeature.geometry;
                    geometry.z = undefined;
                    geometry.hasZ = false;
                    if (geometry.rings != null && geometry.rings[0].length > 1000) {
                        $.messager.alert('提示', '同一要素已做缓冲区太多次，请“清除”后再使用此功能!');
                    } else {
                        var buffer_Geometry = geometry_calculate("buffer", geometry, buffer_distance);
                        add_Draw_Graphic(graphicsLayer_buffer, buffer_Geometry, "polygon");
                    }
                } else {
                    $.messager.alert('提示', '请输入数字!');
                }
            });
            //画图界面查询按钮触发事件
            on(button_draw_chazhi, "click", function () {
                var where = "OBJECTID is not null";
                var query = new Query();
                query.where = where;
                query.returnGeometry = true;
                query.returnZ = true;
                query.outFields = ["*"];

                if (search_geometry) { query.geometry = searchFeature.geometry; }
                var layer_search = myMap.findLayerById("AQI监测点");
                layer_search.queryFeatures(query).then(function (results) {
                    add_aqi_data(results);
                });
            });
            //向获取的AQI监测站添加实时指数属性
            function add_aqi_data(results) {
                var featureSet = results;
                var city = featureSet.features[0].attributes.城市;
                var query_cityname = toPinyin(city);
                $.ajax({
                    url: 'http://api.help.bj.cn/apis/aqi3',
                    async: true,
                    data: {
                        "id": query_cityname
                    },
                    type: 'GET',
                    dataType: 'json',
                    success: function (aqidata) {
                        var zahndian_arry = aqidata.data;
                        for (var j = 0; j < featureSet.features.length; j++) {
                            var zhandianname = featureSet.features[j].attributes.站点;
                            for (var i = 0; i < zahndian_arry.length; i++) {
                                if (zahndian_arry[i].position_name == zhandianname) {
                                    if (zahndian_arry[i].aqi == "_") {
                                        featureSet.features[j].attributes.AQI = 70
                                    } else {
                                        featureSet.features[j].attributes.AQI = parseFloat(zahndian_arry[i].aqi)
                                    }

                                }
                            }
                        }
                        var inputGraphicContainer = [];
                        inputGraphicContainer.push(searchFeature);
                       var  featureSet_mian = new FeatureSet();
                       featureSet_mian.features = inputGraphicContainer;
                       featureSet_mian.features.fields=[
                        {
                         "name": "OBJECTID",
                         "type": "esriFieldTypeOID",
                         "alias": "OBJECTID"
                        },
                        {
                         "name": "SHAPE_Length",
                         "type": "esriFieldTypeDouble",
                         "alias": "SHAPE_Length"
                        },
                        {
                         "name": "SHAPE_Area",
                         "type": "esriFieldTypeDouble",
                         "alias": "SHAPE_Area"
                        }
                       ]
                        var program = {
                            "input": featureSet,
                            "ZValue": Kriging_GP_z_field
                        }
                        Kriging_GP.submitJob(program).then(gpJobComplete);
                    },
                    error: function (e) {
                    },
                });

            }
            //画图功能------具体实现点、线、面的绘画
            function add_Draw_Graphic(graphicsLayer, geometry, type) {
                var actions = Popup_Button_set("缓冲区;范围查询;删除");
                if (type == "point") {
                    Draw_Graphic = new Graphic({
                        geometry: point_click, symbol: MarkerSymbol,
                        popupTemplate: { content: "X: " + point_click.x.toFixed(3) + "</br>Y: " + point_click.y.toFixed(3), actions: actions }
                    });
                    graphicsLayer.add(Draw_Graphic);
                } else if (type == "line") {
                    var length = geometry_calculate("length", geometry);
                    Draw_Graphic = new Graphic({ geometry: geometry, symbol: LineSymbol, popupTemplate: { content: "长度: " + length.toFixed(3) + " 米", actions: actions } });
                    graphicsLayer.add(Draw_Graphic);
                } else if (type == "polygon") {
                    var calculate = geometry_calculate("length&area", geometry, "");
                    var length = calculate.length;
                    var area = calculate.area;
                    Draw_Graphic = new Graphic({
                        geometry: geometry, symbol: PolygonSymbol,
                        popupTemplate: { content: "周长: " + length.toFixed(3) + " 米</br>面积: " + Math.abs(area.toFixed(3)) + " 平方米", actions: actions }
                    });
                    graphicsLayer.add(Draw_Graphic);
                }
                selectedFeature = Draw_Graphic;
                set_button_disable("button_draw_buffer", false);
                if (map_draw_type > 0) {
                    searchFeature = Draw_Graphic;
                    search_geometry_set_new(map_draw_type);
                    set_button_disable("button_draw_chazhi", false);
                }
            }
            //图标颜色选择
            on(select_color, "change", function () {
                var select_color = document.getElementById("select_color").value;
                MarkerSymbol = new SimpleMarkerSymbol({ color: select_color, size: 8, outline: { color: [255, 255, 255], width: 1 } });
                PolygonSymbol = new SimpleFillSymbol({ outline: { color: select_color, width: 2 } });
                LineSymbol = new SimpleLineSymbol({ color: select_color, width: 2 });
            });
            //打印
            var print_widget_show = false;
            var nav_dayin = window.parent.window.document.getElementById("nav_dayin");
            on(nav_dayin, "click", function () {
                if (!print_widget_show) {
                    if (appConfig.activeView.type == "3d") {
                        swapView();
                    }
                    var print = new Print({
                        view: view_2D,
                        printServiceUrl: PrintService_URL,
                        templateOptions: {
                            title: "地图打印",
                            author: "Linser",
                            copyright: "kongxin",
                            legendEnabled: false
                        }
                    });
                    view_2D.ui.add(print, "bottom-left");
                } else {
                    view_2D.ui.empty("bottom-left");
                }
                print_widget_show = !print_widget_show;
            });
            //GP完成之后加载结果图层  
            function gpJobComplete(jobinfo) {
                if (jobinfo.jobStatus == "job-succeeded") {
                    var layer = Kriging_GP.getResultMapImageLayer(jobinfo.jobId);
                    layer.opacity = 0.7;
                    layer.id = "克里金";
                    layer.title = "克里金";
                    myMap.layers.add(layer);
                } else {
                    alert("任务失败")
                }
            }
        });
        //Popup设置
        function Popup_template_set(Popup) {
            var popupTemplate = {};
            if (Popup.Popup_Title != null || Popup.Popup_Title_Name != null) {
                var title;
                if (Popup.Popup_Title_Name != null) {
                    title = Popup.Popup_Title_Name;
                }
                if (Popup.Popup_Title != null) {
                    title = title + Popup_template_set_sub(Popup.Popup_Title);
                }
                popupTemplate.title = title;
            }
            if (Popup.Popup_Button != null) {
                popupTemplate.actions = Popup_Button_set(Popup.Popup_Button);
            }
            if (Popup.Popup_Content != null && Popup.Popup_Title_Name == "（AQI监测点）") {
                popupTemplate.content = Popup_template_content_set;
            } else if (Popup.Popup_Content != null) {
                popupTemplate.content = Popup_template_set_sub(Popup.Popup_Content)
            }
            if (Popup.overwriteActions != null) {
                popupTemplate.overwriteActions = Popup.overwriteActions;
            }
            return popupTemplate;
        }
        //获取线或多边性的 长度和
        function geometry_calculate(type, geometry, input_value) {
            if (type == "length") {
                if (geometry.spatialReference.isWGS84 || geometry.spatialReference.isWebMercator) {
                    return geometryEngine.geodesicLength(geometry, "meters");
                } else {
                    return geometryEngine.planarLength(geometry, "meters");
                }
            } else if (type == "area") {
                if (geometry.spatialReference.isWGS84 || geometry.spatialReference.isWebMercator) {
                    return geometryEngine.geodesicArea(geometry, "square-meters");
                } else {
                    return geometryEngine.planarArea(geometry, "square-meters");
                }
            } else if (type == "buffer") {
                return geometryEngine.buffer(geometry, input_value, "meters");
            } else if (type == "union") {
                return geometryEngine.union(geometry);
            } else if (type == "nearestCoordinate") {
                return geometryEngine.nearestCoordinate(geometry, input_value);
            } else if (type == "distance") {
                return geometryEngine.distance(geometry, input_value, "meters");
            } else if (type == "close_distance") {
                var feature;
                var distance = 30;
                for (var i = 0; i < geometry.length; i++) {
                    var distance_1 = geometryEngine.distance(geometry[i].geometry, input_value, "meters");
                    if (distance_1 <= distance) {
                        distance = distance_1;
                        feature = geometry[i];
                    }
                }
                return feature;
            } else if (type == "length&area") {
                if (geometry.spatialReference.isWGS84 || geometry.spatialReference.isWebMercator) {
                    var result_calculate = {
                        length: geometryEngine.geodesicLength(geometry, "meters"),
                        area: geometryEngine.geodesicArea(geometry, "square-meters")
                    };
                    return result_calculate;
                } else {
                    var result_calculate = {
                        length: geometryEngine.planarLength(geometry, "meters"),
                        area: geometryEngine.planarArea(geometry, "square-meters")
                    };
                    return result_calculate;
                }
            }
        }
    });